<template>
  <div class="dt-select-org">
    <div v-if="tagVisible" class="" style="display:flex;">
      <div class="select-org-click" style="" @click="handleSelectOrg()">
        <div>
          <el-tag v-for="(tag,index) in multipleSelectionChangeOrgData" :key="index" type="info" @close="closeTag(tag)">
            {{ tag.orgName || '' }}
          </el-tag>
          <span v-if="!multipleSelectionChangeOrgData.length" class="plactext">请选择组织</span>
        </div>
      </div>
    </div>
    <div slot="content" class="dt-select-org-body">
      <el-row>
        <!-- 树结构 -->
        <el-col :span="12" :xs="24">
          <div class="mainbox-left">
            <div class="box-card" style="padding: 0 11px;">
              <!-- 搜索栏 -->
              <el-input v-model.trim="filterText" prefix-icon="el-icon-search" placeholder="请输入组织名称" maxlength="30" size="small" style="margin: 0px 0 10px 0;" />
              <div class="treeBox">
                <el-tree
                  ref="tree"
                  :empty-text="$store.getters.dataText"
                  :style="{'--lightOpacity':$store.state.settings.theme + '19'}"
                  class="left-tree"
                  :data="tree"
                  :load="load"
                  lazy
                  :props="defaultProps"
                  :default-expand-all="false"
                  :expand-on-click-node="false"
                  :highlight-current="true"
                  :node-key="defaultProps.id"
                  :check-on-click-node="true"
                  :show-checkbox="true"
                  :check-strictly="true"
                  @check-change="orgTreeCheck"
                >
                  <div slot-scope="{ node}" class="slotSpan">
                    <img src="~@/framework/assets/orgimg.png">
                    <el-tooltip class="item" effect="dark" :open-delay="500" :content="node.label" placement="bottom-start">
                      <span class="tree-name">{{ node.label }}</span>
                    </el-tooltip>
                  </div>
                </el-tree>
              </div>
            </div>
          </div>
        </el-col>
        <!-- 树结构 -->
        <el-col :span="12" :xs="24">
          <div class="mainbox-left mainbox-right">
            <div class="box-card">
              <div>
                <div class="num">
                  <span>已选中：{{ multipleSelectionChangeOrgData.length }}个部门</span>
                  <span class="clearSpan" @click="handleClear">清空</span>
                </div>
                <div v-if="!spanShow || multipleSelectionChangeOrgData.length" class="app_type_list">
                  <div v-for="(item,index) in multipleSelectionChangeOrgData" :key="index" class="already">
                    <img src="~@/framework/assets/orgimg.png">
                    <!-- <span>{{ item.orgName }}</span> -->
                    <div class="list-ptext">
                      <p>{{ item.orgName ||item.name }}</p>
                      <p>{{ item.orgFullPath }}</p>
                    </div>
                    <div style="margin-left: auto;" />
                    <span class="cancle"><i class="el-icon-close el-icon--right" @click="handleCheckedChangeOrg(item)" /></span>
                  </div>
                </div>
                <div v-else style="padding: 12px;font-size: 14px;">同上级管理员组</div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

  </div>
</template>

<script>
import hrOrganizationApi from '@/framework/api/addOrg'
// import { selectDictLabels } from '@/framework/utils/ruoyi'
export default {
  name: 'DtSelectOrg',
  props: {
    spanShow: {
      type: Boolean,
      default: () => {
        return true
      }
    },
    defaultProps: {
      type: Object,
      default: () => {
        return {
          children: 'children',
          label: 'orgName',
          id: 'orgId',
          isLeaf: 'leaf'
        }
      }
    },
    // 弹窗标题
    title: {
      default: '选择组织',
      type: String
    },
    // 接口所需参数
    columnProps: {
      type: Object,
      default: () => {
        return {
          orgName: '',
          orgId: '-1',
          groupId: '', // 当前被授权的管理员组的组ID
          relType: 0 // 0-可授权范围，1-管理范围
        }
      }
    },
    // 接口对象
    api: {
      type: Object,
      default: () => {
        return hrOrganizationApi
      }
    },
    // 是否显示选中tag标签
    tagVisible: {
      type: Boolean,
      default: false
    },
    // 值
    value: { // 选中userIds字符串 '1,2,3'
      type: String,
      default: ''
    },
    // 选中数据数组
    selectData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data: function() {
    return {
      loading: false,
      tree: [],
      multipleSelectionChangeOrgData: [], // 多选选中组织数据
      filterText: '',
      copyParentSelectData: []
    }
  },
  computed: {
    selectIds() {
      const ids = this.tree.map(item => {
        return item[this.defaultProps.id]
      })
      return ids
    }
  },
  watch: {
    value: {
      handler: function(newVal, oldVal) { // 处理回显逻辑
      },
      immediate: true,
      deep: true
    },
    filterText(val) {
      this.columnProps.orgName = val
      if (!val) {
        this.columnProps.orgId = '-1'
      }
      this.api.getParentGroupDataScope(this.columnProps).then((res) => {
        if (val) {
          this.tree = res.data.map(item => {
            return { leaf: true, ...item }
          })
        } else {
          this.tree = res.data
        }
        this.$nextTick(res => {
          this.multipleSelectionChangeOrgData = Object.assign([], this.selectData)
          this.dealSelectPerson()
        })
      })
    }
  },
  created() {
    this.handleSelectOrg()
  },
  methods: {
    handleClear() {
      this.multipleSelectionChangeOrgData = []
      this.$refs.tree.setCheckedNodes([])
    },
    // 打开弹窗
    async handleSelectOrg() {
      this.multipleSelectionChangeOrgData = Object.assign([], this.selectData)
      this.copyParentSelectData = JSON.parse(JSON.stringify(this.multipleSelectionChangeOrgData))
      await this.initTree()
      this.$nextTick(res => {
        this.dealSelectPerson()
      })
    },
    // 回显多选选中数据
    dealSelectPerson() {
      this.$refs.tree.setCheckedNodes(this.multipleSelectionChangeOrgData)
    },
    // 删除选中
    closeTag(tag) {
      this.multipleSelectionChangeOrgData = this.multipleSelectionChangeOrgData.filter(item => item[this.defaultProps.id] !== tag[this.defaultProps.id])
      this.dealParentOrgData()
    },
    // 获取左侧组织树
    async initTree() {
      this.columnProps.orgId = '-1'
      const res = await this.api.getParentGroupDataScope(this.columnProps)
      this.tree = res.data
    },
    /**
     * 处理父组件组织数据
     */
    dealParentOrgData() {
      const orgs = this.multipleSelectionChangeOrgData.map(res => res[this.defaultProps.id]).join(',')
      this.$emit('input', orgs)
      this.$emit('getSelectData', this.multipleSelectionChangeOrgData)
    },
    handleCheckedData() {
      this.multipleSelectionChangeOrgData = [...this.$refs.tree.getCheckedNodes(), ...this.copyParentSelectData] // 处理右侧显示已选treedata
      this.dealParentOrgData()
    },
    // 左侧树选中回调
    orgCheckChange() {
    },
    orgTreeCheck(node, status) {
      this.setDisable(node)
      const temp = (this.$refs.tree.getCheckedNodes() || []).map(item => item[this.defaultProps.id])
      this.copyParentSelectData = this.copyParentSelectData.filter(item => {
        /**
         * 1、已加载出的节点不用管，this.$refs.tree.getCheckedNodes()会获取到正确的值
         * 2、判断该节点的父级集合中是否有“当前选中的node.orgId”,有的话就移除（因为只需保留父节点，子节点不保留)
         * 3、选中条件为false时，应该移除（!(!status && item.orgId === node.orgId)）
         */
        return !this.selectIds.includes(item[this.defaultProps.id]) && !item.orgPids.includes(`[${node[this.defaultProps.id]}]`) && !temp.includes(item[this.defaultProps.id]) && !(!status && item[this.defaultProps.id] === node[this.defaultProps.id])
      })
      this.handleCheckedData()
      // setTimeout(() => {
      // }, 300)
      // this.multipleSelectionChangeOrgData = this.$refs.tree.getCheckedNodes() // 处理右侧显示已选treedata
      // this.dealParentOrgData()
    },
    async setDisable(data) {
      // const list = []
      // const orgList = this.$refs.tree.getCheckedNodes()
      // for (let i = 0; i < orgList.length; i++) {
      //   list.push(orgList[i].id)
      // }
      // this.grantidList = list

      const node = this.$refs.tree.getNode(data)
      if (node.checked || node.data.disabled) { // 判断是否禁用子节点--禁用
        await this.$nextTick()
        this.dealTreeData(node, !node.data.disabled)
      } else {
        this.dealTreeData(node, false)
      }
    },
    // 递归处理treeData
    dealTreeData(node, status) {
      setTimeout(() => {
        node.childNodes.forEach(res => {
          this.setDisabledTreeData(node.childNodes, res[this.defaultProps.id], status)
          if (res.childNodes && res.childNodes.length > 0) {
            this.dealTreeData(res, status)
          }
        })
      }, 200)
    },
    /**
     * 禁用节点
     * @param {*} data
     * @param {*} id 值不为undefined设置禁用节点；反之则清除禁用节点
     * @param {*} status true 禁用  false 不禁用
     */
    setDisabledTreeData(data, id, status) {
      data.forEach((item) => { // 遍历整个树 数据
        this.$set(item.data, 'disabled', status)
        status && this.$refs.tree.setChecked(item, false)
        // this.handleCheckedData()
      })
    },
    // 删除组织
    handleCheckedChangeOrg(val) {
      this.multipleSelectionChangeOrgData = this.multipleSelectionChangeOrgData.filter(item => {
        return item[this.defaultProps.id] !== val[this.defaultProps.id]
      })
      this.copyParentSelectData = this.copyParentSelectData.filter(item => item[this.defaultProps.id] !== val[this.defaultProps.id])
      this.$refs.tree.setCheckedNodes(this.multipleSelectionChangeOrgData)
      this.dealParentOrgData()
    },
    load(tree, resolve) {
      let id = 0
      if (!tree.data || tree.data.length === 0) {
        return
      } else {
        // id = tree.data.id
        id = tree.data[this.defaultProps.id]
      }
      this.columnProps.orgId = id
      this.api.getParentGroupDataScope(this.columnProps).then((res) => {
        const data = res.data.map((item, index) => {
          this.$nextTick(() => {
            this.$refs.tree.setCheckedNodes(this.multipleSelectionChangeOrgData)
          })
          return item
        })
        resolve(data)
        // if (id === 0) {
        //   resolve(res.data[0].children)
        // } else if (id === 1) {
        //   resolve(res.data[0].children[0].children)
        // } else {
        //   resolve(res.data[0].children[0].children)
        // }
        // this.$nextTick(() => {
        //   this.$refs.tree.setCheckedNodes(this.multipleSelectionChangeOrgData)
        // })
        if (tree.checked || tree.data.disabled) { // 判断是否禁用子节点
          this.$nextTick()
          this.dealTreeData(tree, true)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.slotSpan {
    display: flex;
    flex-direction: row;
    /*文字居于图片上方*/
    justify-content: center;

    /*图片垂直居中*/
    img {
        margin-right: 6px;
    }

    span {
        //line-height: 36px;
        margin-top: 5px;
    }
}

.treeBox {
    height: 320px;
    overflow: auto;
}

::v-deep .el-tree-node__content {
    height: 36px;
    //line-height: 36px;
}

.dt-select-org {
    .select-org-click {
        border: 1px #c0c4cc solid;
        border-radius: 5px;
        cursor: pointer;
        // min-height:40px;
        width: 100%;
        height: 100%;
        padding: 0px 8px 0 8px;
        // line-height: 28px;
        margin: auto;
        min-height: 36px;
        line-height: 36px;
        min-width: 200px;

        >div {
            margin: auto;
        }

        .el-tag {
            margin-right: 5px;
            margin-bottom: 4px;
        }
    }

    .isDisabled {
        background-color: #F5F7FA !important;
        border-color: #E4E7ED !important;
        color: #C0C4CC !important;
        cursor: not-allowed !important;
    }

    .plactext {
        color: #DCDFE6;
    }
}

::v-deep .el-dialog__header {
    padding-bottom: 5px !important;
}

::v-deep .dt-select-org-body {
    flex: 1;
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border: solid 1px #DCDFE6;
    margin-top: 10px;
    background-color: white;
    border-radius: 4px;

    >.el-row {
        display: flex;
        flex: 1;
        flex-wrap: wrap;

        >.el-col {
            .mainbox-left {
                height: 100%;
                display: flex;
                flex-direction: column;

                flex: 1;
                border-radius: 5px;

                // background: #f8f9fa;
                >.box-card {
                    height: 100%;
                    min-height: 400px;
                    border-radius: 0!important;
                    display: flex;
                    flex-direction: column;
                    //padding: 0 12px;
                    margin: 12px;
                    margin-right: 0;
                    // margin-right: 2px;
                    background: #fff;
                    webkit-box-shadow: none!important;
                    box-shadow: none!important;
                    // box-shadow: 0px 4px 8px 2px rgba(0, 0, 0, 0.04),
                    //   0px 2px 6px 0px rgba(0, 0, 0, 0.06), 0px 0px 4px 0px rgba(0, 0, 0, 0.08);

                    .el-table {
                        flex: 1;
                    }
                }

                .already {

                    display: flex;
                    align-items: center;
                    margin: 8px 0 0 0px;
                    cursor: pointer;
                    justify-content: flex-start;

                    img {
                        margin-right: 8px;
                    }

                    .list-ptext {
                        p {
                            padding: 0;
                            margin: 0;
                        }

                        p:last-child {
                            font-size: 12px;
                            color: #909399;
                        }

                    }

                }

                .already:hover {
                    color: rgb(52, 97, 255);
                }

                .num {
                    color: #131414;
                    // margin-left: 14px;
                    // margin-bottom: 16px;
                    padding: 0 12px 12px 12px;
                    border-bottom: solid 1px #DCDFE6;
                    font-size: 14px;

                    .clearSpan {
                        float: right;
                        color: #3461FF;
                        cursor: pointer;
                    }
                }
            }

            .mainbox-right {
                >.box-card {
                    //margin: 12px 0;
                    border-left: solid 1px #DCDFE6;
                }

                .app_type_list {
                    padding: 8px 12px;

                    .already {
                        font-size: 14px;
                    }
                }
            }

            .mainbox-left {
                .box-card {
                    margin-left: 0;
                }
            }
        }
    }

    .mainbox {
        height: 100%;
        display: flex;
        flex-direction: column;
        flex: 1;
        // max-height: calc(100vh - 100px);
        // background: #fff;
        border-radius: 5px;
        padding: 16px;
        // padding-left: 0px;
        // background: #f8f9fa;

        //搜索区域
        .filter-container {
            background: #fff;
            border-radius: 4px;
            margin-bottom: 16px;
            padding: 20px 16px;
            padding-bottom: 0;
            display: flex;
            justify-content: flex-start;
            box-shadow: 0px 4px 8px 2px rgba(0, 0, 0, 0.04),
                0px 2px 6px 0px rgba(0, 0, 0, 0.06), 0px 0px 4px 0px rgba(0, 0, 0, 0.08);
            flex-wrap: wrap;

            .filter-item {
                display: inline-block;
                vertical-align: middle;
                // margin-left: 10px;
            }

            .el-form {
                .el-form-item {
                    // margin-bottom: 0;
                }
            }

            .el-button {
                align-self: flex-start;
                margin-bottom: 16px;
            }
        }

        //表格区域
        .table-container {
            display: flex;
            border-radius: 4px;
            flex-direction: column;
            background: #fff;
            padding: 16px;
            flex: 1;
            box-shadow: 0px 4px 8px 2px rgba(0, 0, 0, 0.04),
                0px 2px 6px 0px rgba(0, 0, 0, 0.06), 0px 0px 4px 0px rgba(0, 0, 0, 0.08);

            //表格操作区域
            .table-opt-container {
                display: flex;
                align-items: center;
                margin-bottom: 8px;

                .el-button {
                    margin-bottom: 8px;
                }
            }

            .el-table {
                flex: 1;

                .cell {
                    padding-left: 16px !important;
                    padding-right: 16px !important;

                }
            }
        }

        .demo-form-inline {
            display: flex;
            justify-content: flex-end;
        }

        .el-table {
            // min-height: calc(100vh - 270px);
            // max-height: calc(100vh - 270px);
            // overflow: scroll;
        }
    }

}

::v-deep .el-dialog {
    border-radius: 4px;
}
</style><style lang="scss">
.el-form-item.is-error .dt-select-org .el-input__inner {
    border-color: #DCDFE6;
}

.is-error {
    .dt-select-org {
        .select-org-click {
            border-color: #F56C6C !important;
        }
    }
}
</style>
